package source

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"net/url"
	"os"
)

const (
	JinshanKey     = "AA4FE24DB900CAA557244BF78A9C211E"
	JInshanBaseUrl = "http://dict-co.iciba.com/api/dictionary.php"
)

type JinshanRespose struct {
	Word_name string
	Symbols   []JinshanTransResult
}

type JinshanTransResult struct {
	Word_symbol string
	Parts       []Parts
}
type Parts struct {
	Means []Means
}

type Meanstype struct {
	word_mean string
	has_mean  string
	split     int
}
type Means interface{}

// 金山词霸源翻译
func TranslateJinshan(q, fromType string) []string {
	var wordMeans []string
	h := md5.New()
	salt := GetRandomSalt()
	h.Write([]byte((appid + q + salt + scret)))

	queryWord := url.QueryEscape(q)
	url := JInshanBaseUrl + "?w=" + queryWord + "&key=" + JinshanKey + "&type=json"
	// fmt.Println(url)
	body, err := GetJson(url)
	if err != nil {
		fmt.Println("返回结果出错", err)
	}

	var r JinshanRespose
	if err2 := json.Unmarshal(body, &r); err2 != nil {
		fmt.Println("返回结果出错", err2)
	}

	// fmt.Printf(" ~ %s \n", r.Word_name)
	// fmt.Println("结果:")

	//获取翻译结果
	results := r.Symbols[0]
	if len(results.Parts) == 0 {
		fmt.Println(" Sorry, unable to find the result")
		os.Exit(0)
	}
	result := results.Parts[0].Means

	for i := 0; i < len(result); i++ {
		mean := result[i]
		switch v := mean.(type) {
		case map[string]interface{}:
			if wm, ok := v["word_mean"]; ok {
				wordMeans = append(wordMeans, fmt.Sprintf("%s", wm))
			}
			break
		case string:
			wordMeans = append(wordMeans, v)
			// fmt.Printf("%d:  "+v+"\n", i+1)
			break
		default:
			wordMeans = append(wordMeans, fmt.Sprintf("%s", v))
		}
	}

	return wordMeans
}
